package com.scrx.ymg.service.seckill;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.scrx.ymg.dao.agent.IAgentInfoDao;
import com.scrx.ymg.dao.head.IHeadDao;
import com.scrx.ymg.dao.orderform.IOrderFormDao;
import com.scrx.ymg.dao.seckill.ISeckillDao;
import com.scrx.ymg.dao.supermarket.ISuperMarketDao;
import com.scrx.ymg.dao.user.IUserDao;
import com.scrx.ymg.entity.AgentInfo;
import com.scrx.ymg.entity.AgentMoney;
import com.scrx.ymg.entity.BodyCount;
import com.scrx.ymg.entity.DividedInto;
import com.scrx.ymg.entity.HeadMoney;
import com.scrx.ymg.entity.HeadWithdarw;
import com.scrx.ymg.entity.OrderForm;
import com.scrx.ymg.entity.OrderFormDetails;
import com.scrx.ymg.entity.OtherInfo;
import com.scrx.ymg.entity.OtherMoney;
import com.scrx.ymg.entity.SeckillProduct;
import com.scrx.ymg.entity.SupermarketMoney;
import com.scrx.ymg.entity.User;
import com.scrx.ymg.util.BaseUtil;
import com.scrx.ymg.util.LatLonUtil;

@Service("seckillService")
public class SeckillServiceImpl implements ISeckillService {
    
	@Autowired
	private ISeckillDao seckilldao;
	@Autowired
	private IUserDao userdao;
	@Autowired
	private IOrderFormDao orderdao;
	@Autowired
	private IAgentInfoDao agentdao;
	@Autowired
	private IHeadDao headao;
	@Autowired
	private ISuperMarketDao superMarketDao;
	
	

	public List<SeckillProduct> getSeckillList(int agentID) {

		return seckilldao.getSeckillList(agentID);
	}
	
	public SeckillProduct getSeckillOne(int id) {

		return seckilldao.getSeckillOne(id);
	}

	
	public String createSeckillOrderForm(int seckillID, int userID,int num,int typeId) {
		  User user=userdao.findById(userID);
		  SeckillProduct seckill=seckilldao.getSeckillOne(seckillID);
		  String msg="false";
		  if(seckill.getInventory()<=0){
			  return "251";
		  }
		  if(user!=null&&seckill!=null&&seckill.getInventory()>0){
			  OrderForm order=new OrderForm();
			  OrderFormDetails orders=new OrderFormDetails();
			  SimpleDateFormat  formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
			  String orderid=orderIDGenerativeRule(userID, seckill.getOtherId());
			  order.setInactive1(2);
			  order.setInactive2(seckill.getStoreName());
			  //order.setOrderFormDetails(orderFormDetails);
			  order.setOrderFormId(orderid);
			  order.setOrderFormTime(formatter.format(new Date()));
			  order.setPaymentType(2);
			  order.setTypeId(typeId);//秒杀商品
			 // order.setPhone(user.getPhone().toString());
			  order.setStatus(2);
			  //order.setSeckillId(seckillId);
			  order.setTotalMoney(seckill.getSeckillPrice());
			  order.setUserId(user.getId());
			  order.setUserName(user.getUserName());
			  order.setSuperId(seckill.getOtherId());
			  order.setCode(verificationCode(user.getId(), seckill.getOtherId()));
			  seckill.setInventory(seckill.getInventory()-1);
			  msg=seckilldao.saveandUpdate(seckill,order,num);
		  }
		  
		return msg;
	}
	
	/**
	 * 订单编号生成规则
	 * @param userID
	 * @param superID
	 * @return
	 */
	public String orderIDGenerativeRule(int userID,int agentId){
		SimpleDateFormat  formatter = new SimpleDateFormat ("yyMMddHHmmss");
		String date=formatter.format(new Date());
		String orderid="t"+agentId+date+userID;
		return orderid;
	}
	
	/**
	 * 团购核销码
	 * @param userID
	 * @param ohterId
	 * @return
	 */
	public String verificationCode(int userID,int ohterId){
		SimpleDateFormat  formatter = new SimpleDateFormat ("HHmmss");
		String date=formatter.format(new Date());
		String Code=ohterId+date+random(4)+userID;
		return Code;
	}
	 public  String random(int n) {
	        if (n < 1 || n > 10) {
	            throw new IllegalArgumentException("cannot random " + n + " bit number");
	        }
	        Random ran = new Random();
	        if (n == 1) {
	            return String.valueOf(ran.nextInt(10));
	        }
	        int bitField = 0;
	        char[] chs = new char[n];
	        for (int i = 0; i < n; i++) {
	            while(true) {
	                int k = ran.nextInt(10);
	                if( (bitField & (1 << k)) == 0) {
	                    bitField |= 1 << k;
	                    chs[i] = (char)(k + '0');
	                    break;
	                }
	            }
	        }
	        return new String(chs);
	    }


	public String getSeckillOrderForm(int userID,int productId) {
		OrderFormDetails detals= seckilldao.getSeckillOrderForm(userID,productId);
		if (detals==null) {
			return "true";
		}else{
			return "false";
		}
	}


	public String insertSeckillOne(SeckillProduct product,MultipartFile productFile,MultipartFile publicityFile,MultipartFile detailFile) {
		SeckillProduct oldproduct = seckilldao.getSeckillOneByProductName(product.getProductName());
		SeckillProduct dateproduct =seckilldao.getSeckillByDateAndAgentId(product.getStartDate(), product.getAgentId());
		if(dateproduct!=null){
			return "251";
		}
		if(oldproduct==null){
			OtherInfo info =seckilldao.getOtherInfoById(product.getOtherId());
			product.setAddress(info.getOtherAdd());
			product.setPhone(info.getOtherPhone());
			String seckills = BaseUtil.seckillsPath;
            
			String detailFileName=BaseUtil.addRandom(detailFile.getOriginalFilename());
			String detailFilePath = seckills + detailFileName;
			product.setDetailImg(detailFileName);
			
			String productFileName=BaseUtil.addRandom(productFile.getOriginalFilename());
			String productFilePath = seckills + productFileName;
			product.setProductImg(productFileName);
			
			String publicityFileName=BaseUtil.addRandom(publicityFile.getOriginalFilename());
			String publicityFilePath = seckills + publicityFileName;
			product.setPublicityImg(publicityFileName);
			
			product.setStatus(0);
			product.setSales(0);
			HeadWithdarw head=headao.getHeadWithdarw();
			product.setAdPrice(head.getAdRate());
			return seckilldao.saveSeckillProduct(product,productFile,productFilePath,publicityFile,publicityFilePath,detailFile,detailFilePath);
		}else{
			return "250";
		}
		
	}


	public String updateSeckillOne(SeckillProduct product,MultipartFile productFile,MultipartFile publicityFile,MultipartFile detailFile) {
		String seckills = BaseUtil.seckillsPath;
		String productFilePath="";
		String publicityFilePath ="";
		String detailFilePath="";
		SeckillProduct oldProduct = seckilldao.getSeckillOne(product.getId());
		if(oldProduct.getTypeId().intValue()==0&&oldProduct.getStatus()==1){
			return "251";
		}
		product.setTypeId(oldProduct.getTypeId());
		product.setStoreName(oldProduct.getStoreName());
		product.setAddress(oldProduct.getAddress());
		product.setPhone(oldProduct.getPhone());
		if(detailFile.getSize()>0){
			String detailFileName=BaseUtil.addRandom(detailFile.getOriginalFilename());
			detailFilePath = seckills + detailFileName;
			product.setDetailImg(detailFileName);
		}else{
			product.setDetailImg(oldProduct.getProductImg());
		}
		
		if(productFile.getSize()>0){
			String productFileName=BaseUtil.addRandom(productFile.getOriginalFilename());
			productFilePath = seckills + productFileName;
			product.setProductImg(productFileName);
			
		}else{
			product.setProductImg(oldProduct.getProductImg());
		}
		
		if(publicityFile.getSize()>0){
			String publicityFileName=BaseUtil.addRandom(publicityFile.getOriginalFilename());
			publicityFilePath = seckills + publicityFileName;
			product.setPublicityImg(publicityFileName);
		}else{
			product.setPublicityImg(oldProduct.getPublicityImg());
		}
		return seckilldao.updateSeckillOne(product,productFile,productFilePath,publicityFile,publicityFilePath,detailFile,detailFilePath);
	}


	public String deleteSeckillOne(SeckillProduct product) {
		product =seckilldao.getSeckillOne(product.getId());
		return seckilldao.deleteSeckillOne(product);
	}

	public Map<Object, Object> selectSeckillProductList(SeckillProduct product, int pageNum, int pageCount,String startTime,String endTime) {

		return seckilldao.selectSeckillProductList(product,pageNum,pageCount,startTime,endTime);
	}


	public List<OtherInfo> getOtherInfo(OtherInfo info) {
		return seckilldao.getOtherInfo(info);
	}


	public String putawaySeckillProduct(SeckillProduct product) {
		SeckillProduct oldproduct =seckilldao.getSeckillOne(product.getId());
		oldproduct.setStatus(product.getStatus());
		return seckilldao.updateSeckillOne(oldproduct, null, null, null, null,null,null);
	}


	public String applyCheckSeckillProduct(String orderNum) {
		//SeckillProduct oldproduct =seckilldao.getSeckillOne(SeckillProductId);
		SeckillProduct oldproduct =seckilldao.getSeckillOneByOrderNum(orderNum);
		/*利润分配*/
		DividedInto into = headao.selectDividedInto();//1.得到分成设置
		double agent_fc=into.getAgentAdDivided();//代理商广告分成比例
		double head_fc=into.getHeadAdDivided();//总部广告分成比例
		
		double agentgetMoney=0;//代理商可得金额
		double head_getMoney=0;//总部可得金额
		double adPrice=oldproduct.getAdPrice();//广告价格
		if(oldproduct!=null){
		if(oldproduct.getTypeId()==0){//秒杀广告订单
			/*根据金额给各商家分成*/
			//2.代理商
            AgentMoney agentMoney = agentdao.getAgentMoneyInfo(oldproduct.getAgentId());
            double agentMoney_fc=adPrice*agent_fc/100;//代理商
            agentMoney.setAgentAdMoney(agentMoney.getAgentAdMoney()+agentMoney_fc);
            agentMoney.setAccountMoney(agentMoney.getAccountMoney()+agentMoney_fc);
            agentMoney.setTotalMoney(agentMoney.getTotalMoney()+agentMoney_fc);
			//3.总部
            HeadMoney headMoney = headao.getHeadMoney();
            double headMoney_fc=adPrice*head_fc/100;
            headMoney.setHeadAdMoney(headMoney.getHeadAdMoney()+headMoney_fc);
            headMoney.setHeadAccountMoney(headMoney.getHeadAccountMoney()+headMoney_fc);
            headMoney.setHeadTotalMoney(headMoney.getHeadTotalMoney()+headMoney_fc);
            //4.平台
            headMoney.setTerraceAdMoney(headMoney.getTerraceAdMoney()+adPrice);//平台广告营业总金额
            headMoney.setTerraceAccountMoney(headMoney.getTerraceAccountMoney()+adPrice);//平台可提现金额
            headMoney.setTerraceTotalMoney(headMoney.getTerraceTotalMoney()+adPrice);//平台营业总金额
			/*根据金额给各商家分成*/
          //3.事务保存
            oldproduct.setStatus(3);
          return orderdao.updateByAd(oldproduct,agentMoney,headMoney);
		}
		}
		
		
		
		
		
		return seckilldao.updateSeckillOne(oldproduct, null, null, null, null, null, null);
	}

	public String verificationCode(OrderForm order) {
		OrderForm oldorder = orderdao.getOrderFormByID(order.getId());
		DividedInto into = headao.selectDividedInto();//1.得到分成设置
		User user =userdao.findById(oldorder.getUserId());
		double agent_fc=into.getAgentTgDivided()/100;//代理商分成比例
		double super_fc=into.getSuperTgDivided()/100;//超市分成比例
		double head_fc=into.getHeadTgDivided()/100;//总部分成比例
		
		double othergetMoney=0;//异业商家可得金额
		double qt_getMoney=0;//超市,总部,代理商家可得金额
		
		
		if(oldorder!=null){
		if(oldorder.getTypeId()==2){//团购订单
			oldorder.setStatus(3);
			/*异业商家营业额入账*/
			OtherInfo other=seckilldao.getOtherInfoById(oldorder.getSuperId());//异业商家id
			double percentage =(100-other.getDistributionProfits())/100;//异业商家可得分配比率
			double qt_percentage=other.getDistributionProfits()/100;//其他商家可得分配比率
			qt_getMoney =oldorder.getTotalMoney()*qt_percentage;
			othergetMoney =oldorder.getTotalMoney()*percentage;
			OtherMoney otherMoney = seckilldao.getOtherMoney(other.getId());
			otherMoney.setAccountMoney(otherMoney.getAccountMoney()+othergetMoney);
			otherMoney.setTotalMoney(otherMoney.getTotalMoney()+othergetMoney);
			/*异业商家营业额入账*/
			
			/*根据金额给各商家分成*/
			//2.代理商
            AgentMoney agentMoney = agentdao.getAgentMoneyInfo(oldorder.getAgentId());
            double agentMoney_fc=qt_getMoney*agent_fc;//超市可分得利润
            agentMoney.setGroupMoney(agentMoney.getGroupMoney()+agentMoney_fc);
            agentMoney.setAccountMoney(agentMoney.getAccountMoney()+agentMoney_fc);
            agentMoney.setTotalMoney(agentMoney.getTotalMoney()+agentMoney_fc);
			//3.总部
            HeadMoney headMoney = headao.getHeadMoney();
            double headMoney_fc=qt_getMoney*head_fc;
            headMoney.setHeadGroupMoney(headMoney.getHeadGroupMoney()+headMoney_fc);
            headMoney.setHeadAccountMoney(headMoney.getHeadAccountMoney()+headMoney_fc);
            headMoney.setHeadTotalMoney(headMoney.getHeadTotalMoney()+headMoney_fc);
            
			//1.超市
			
			if(user.getBelongSupermarket()==null){
				   double superMoney_fc=qt_getMoney*super_fc;//超市可分得利润
				   headMoney.setHeadGroupMoney(headMoney.getHeadGroupMoney()+superMoney_fc);
		           headMoney.setHeadAccountMoney(headMoney.getHeadAccountMoney()+superMoney_fc);
		           headMoney.setHeadTotalMoney(headMoney.getHeadTotalMoney()+superMoney_fc);
				return orderdao.updateObjects(oldorder,otherMoney,null,agentMoney,headMoney);
			}else{
	            SupermarketMoney superMoney =superMarketDao.getSupermarketMoneyInfo(user.getBelongSupermarket());
	            double superMoney_fc=qt_getMoney*super_fc;//超市可分得利润
	            superMoney.setGroupMoney(superMoney.getGroupMoney()+superMoney_fc);//超市团购提成记录
	            superMoney.setAccountMoney(superMoney.getAccountMoney()+superMoney_fc);//超市可提现金额
	            superMoney.setTotalMoney(superMoney.getTotalMoney()+superMoney_fc);
	            return orderdao.updateObjects(oldorder,otherMoney,superMoney,agentMoney,headMoney);
			}
			/*根据金额给各商家分成*/

		}else if(oldorder.getTypeId()==0){
			oldorder.setStatus(3);
			return orderdao.update(oldorder);
		}
		}
		
		return "false";
	}


	public String updateOtherInfo(OtherInfo info,String oldPassWord, String newPassWord) {
		OtherInfo oldinfo = seckilldao.getOtherInfoById(info.getId());
		if(oldPassWord.equals(oldinfo.getPassWord())){
			oldinfo.setPassWord(newPassWord);
			return seckilldao.updateOtherInfo(oldinfo);
		}
		return "250";
	}


	public OtherMoney getOtherMoney(int otherId) {

		return seckilldao.getOtherMoney(otherId);
	}


	public Map<Object, Object> getSeckillProductByAgent(SeckillProduct product, String postId, int pageNum, int pageCount) {
		AgentInfo  info = agentdao.getAgentInfoByagentRegion(postId);
		if(info!=null){
			product.setAgentId(info.getId());
			return seckilldao.selectSeckillProductList(product,pageNum,pageCount,null,null);
		}
		return null;
	}


	public List<SeckillProduct> getSeckillListByPostalcode(String postId) {
		AgentInfo  info = agentdao.getAgentInfoByagentRegion(postId);
		if(info!=null){
			return seckilldao.getSeckillList(info.getId());
		}
		return null;
	}


	public void insertbodyCount(BodyCount bodyCount) {
		LatLonUtil util =new LatLonUtil();
		bodyCount.setStatsDate(util.newdateNoTime());
		BodyCount oldbodyCount=seckilldao.getBodyCount(bodyCount);
		if(oldbodyCount!=null){
			oldbodyCount.setBodyCount(oldbodyCount.getBodyCount()+1);
			String msg = seckilldao.updateBodyCount(oldbodyCount);
		}else{
			BodyCount count=new BodyCount(null, bodyCount.getAgentId(),
					1, util.newdateNoTime(), bodyCount.getSeckillId());
			String msg = seckilldao.insertBodyCount(count);
		}
		
	}


	public String createSeckillOrderForm(String out_trade_no, int seckillID, int userID, int num,
			int typeId) {
		 User user=userdao.findById(userID);
		  SeckillProduct seckill=seckilldao.getSeckillOne(seckillID);
		  String msg="false";
		  if(user!=null&&seckill!=null){
			  OrderForm order=new OrderForm();
			  OrderFormDetails orders=new OrderFormDetails();
			  SimpleDateFormat  formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
			  order.setInactive1(2);
			  order.setInactive2(seckill.getStoreName());
			  //order.setOrderFormDetails(orderFormDetails);
			  order.setOrderFormId(out_trade_no);
			  order.setOrderFormTime(formatter.format(new Date()));
			  order.setPaymentType(2);
			  order.setTypeId(typeId);
			 // order.setPhone(user.getPhone().toString());
			  order.setStatus(-1);
			  //order.setSeckillId(seckillId);
			  order.setTotalMoney(seckill.getSeckillPrice()*num);
			  order.setUserId(user.getId());
			  order.setUserName(user.getUserName());
			  order.setSuperId(seckill.getOtherId());
			  order.setAgentId(seckill.getAgentId());
			  order.setCode(verificationCode(user.getId(), seckill.getOtherId()));
			  seckill.setInventory(seckill.getInventory()-1);
			  msg=seckilldao.saveandUpdate(seckill,order,num);
		  }
		return msg;
	
	}


	public String checkAdById(int seckillId, int status) {
		SeckillProduct product =seckilldao.getSeckillOne(seckillId);
		SeckillProduct oldProduct=seckilldao.getSeckillByDateAndAgentId(product.getStartDate(),product.getAgentId());
		if(oldProduct==null){
			product.setStatus(status);
			return seckilldao.updateSeckillOne(product, null, null, null, null, null, null);
		}else if(oldProduct.getStatus()==0){
			product.setStatus(status);
			return seckilldao.updateSeckillOne(product, null, null, null, null, null, null);
		}else{
			return "251";
		}
	}
	public Map<Object, Object> getOtherInfo(OtherInfo info, int pageNum, int pageCount) {
		return seckilldao.getOtherInfo(info,pageNum, pageCount);
	}


	public String checkOtherInfo(OtherInfo other) {
		OtherInfo oldother = seckilldao.getOtherInfoById(other.getId());
		OtherMoney  newmoney= new OtherMoney();
		if(oldother!=null){
			oldother.setOtherStatus(other.getOtherStatus());
			OtherMoney money = seckilldao.getOtherMoney(oldother.getId());
			if(money==null){
				newmoney.setAccountMoney(0.0);
				newmoney.setOtherId(oldother.getId());
                newmoney.setTotalMoney(0.0);
			}
		}
		return seckilldao.updateOtherInfo(oldother,newmoney);
	}


	public String deleteOtherInfo(OtherInfo other) {
		OtherInfo oldother = seckilldao.getOtherInfoById(other.getId());
		return seckilldao.deleteOtherInfo(oldother);
	}


	public String updateOtherInfoByStatus(OtherInfo other) {
		OtherInfo oldother = seckilldao.getOtherInfoById(other.getId());
		oldother.setOtherStatus(other.getOtherStatus());
		return  seckilldao.updateOtherInfo(oldother);
	}

	public String saveSeckill(SeckillProduct seckill) {

		return seckilldao.saveSeckill(seckill);
	}


	public String updateSeckillProduct(SeckillProduct seckill) {
		return seckilldao.updateSeckillProduct(seckill);
	}
	
	public String updateSeckillProductAD(String thisTime){
		return seckilldao.updateSeckillProductAD(thisTime);
	}


	public OtherInfo getOtherInfoById(Integer id) {
		return seckilldao.getOtherInfoById(id);
	}

}
